import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:second_hand/data/shared_preferences_service.dart';
import 'package:second_hand/API/user/user.dart';

class UserController extends GetxController {
  // 用户信息响应式变量
  RxBool isReady = false.obs;
  RxInt id = 0.obs;
  RxString phone = ''.obs;
  RxString name = ''.obs;
  RxString studentId = ''.obs;
  RxString campus = ''.obs;
  RxString pictureUrl = ''.obs;
  RxInt credit = 0.obs;
  RxString createTime = ''.obs;
  RxString updateTime = ''.obs;

  // 获取用户信息（自动处理token）
  Future<bool> getUserInfo() async {
    try {
      final token = await SharedPreferencesService.getToken();
      if (token == null || token.isEmpty) {
        if (kDebugMode) {
          print("token为空");
        }
        isReady.value = false;
        return false;
      }

      final response = await ApiService.getUserInfo(token);

      if (response["code"] == 20041) {
        if (kDebugMode) {
          print("获取用户信息成功");
          print("token: $token");
        }
        final data = response["data"];
        id.value = data['id'];
        phone.value = data['phone'];
        name.value = data['name'];
        studentId.value = data['student_id'];
        campus.value = data['campus'];
        pictureUrl.value = data['picture'];
        credit.value = data['credit'];
        createTime.value = data['create_time'];
        updateTime.value = data['update_time'];
        isReady.value = true;

        return true;
      } else {
        _handleError("获取用户信息失败: ${response['message']}");
        return false;
      }
    } catch (e) {
      isReady.value = false;
      _handleError("网络请求失败: $e");
      return false;
    }
  }
  // 新增：更新用户部分信息
  Future<bool> updateUserNameCampus({
    required String name,
    required String campus,
  }) async {
    try {
      final response = await ApiService.updateUserInfo(
        name: name,
        campus: campus,
      );

      if (response['code'] == 20031) {
        await getUserInfo(); // 刷新最新数据 [[3]]
        return true;
      } else {
        _handleError("更新失败: ${response['message']}");
        return false;
      }
    } catch (e) {
      _handleError("网络请求失败: $e");
      return false;
    }
  }

  // 统一错误处理
  void _handleError(String message) {
    if (kDebugMode) print(message);
    Get.snackbar(
      "获取个人信息错误",
      message,
      duration: const Duration(seconds: 4),
      snackPosition: SnackPosition.TOP,
    );
  }

}